package eerbaar.action.internal.lib;

import java.util.Map;

import eerbaar.area.IArea;
import eerbaar.context.IContext;
import eerbaar.context.IParams;
import eerbaar.elements.IElement;
import eerbaar.game.IGame;
import eerbaar.position.IPosition;
import eerbaar.position.WrongPositionException;

public class SetPositionAction extends AbstractAction {

    private static final String[] paramNames = new String[] { //
    "name", "position" //
    };

    private String name;
    private String position;
    private IParams params;

    public SetPositionAction(IParams params) {
        super("setPosition");
        this.params = params;

        setup(params);
    }

    @Override
    public void execute(IContext model) {

        IGame game = (IGame) model;
        IArea area = game.getArea();

        IElement[] elements = area.getElements();
        for (IElement e : elements) {

            if (!e.getName().equals(this.name)) {
                continue;
            }

            IPosition p = Global.calcInputPosition(this.position, area);
            if (p == null) {
                break;
            }

            try {
                e.setPosition(p);
            } catch (WrongPositionException e1) {
            }

            break;
        }

    }

    @Override
    public void execute(IContext model, Map<String, String> map) {
        execute(model);
    }

    @Override
    public String[] getParamNames() {

        return paramNames;
    }

    @Override
    public IParams getParams() {

        return this.params;
    }

    @Override
    public void setParams(IParams params) {
        this.params = params;
        setup(params);
    }

    private void setup(IParams params) {

        this.name = params.get("name");
        this.position = params.get("position");
    }
}
